package com.roc.steelend.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roc.steelend.controller.vo.common.KaiPingByRecoding;
import com.roc.steelend.controller.vo.common.PingBanSaleBuyOrderDetailVo;
import com.roc.steelend.controller.vo.kaiping.KaipingOrderDetailVo;
import com.roc.steelend.controller.vo.kaiping.KaipingOrderVo;
import com.roc.steelend.controller.vo.returnformat.ReturnMsg;
import com.roc.steelend.mapper.*;
import com.roc.steelend.pojo.*;
import com.roc.steelend.service.KaipingOrderService;
import com.roc.steelend.util.LshUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.convert.DataSizeUnit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor =  Exception.class)
public class KaipingOrderServiceImpl  implements KaipingOrderService {

    @Autowired
    private KaipingGuyMapper kaipingGuyMapper;

    @Autowired
    private KaipingOrderMapper kaipingOrderMapper;

    @Autowired
    private KaipingDetailMapper kaipingDetailMapper;

    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private SmallTypeMapper smallTypeMapper;

    //  平板库存查询wrapper
    private static QueryWrapper<Inventory> PingBanWrapperUtil(KaipingDetail kaipingDetail, Integer warehouseId) {
        QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
        wrapper.eq("warehouse_id",warehouseId);
        wrapper.eq("small_type_id",kaipingDetail.getSmallTypeId());
        wrapper.eq("thickness",kaipingDetail.getThickness());
        wrapper.eq("long1",kaipingDetail.getLong1());
        wrapper.eq("wide",kaipingDetail.getWide());
        wrapper.eq("high",kaipingDetail.getHigh());
        return wrapper;
    }

    @Override
    public ReturnMsg addKaipingOrderService(KaipingOrderVo kaipingOrderVo, Integer employeeId) {
        //
        Boolean tempByKaipingGuyInsert = false;
        if (kaipingOrderVo.getIsNewKaiPingGuy()) {
            KaipingGuy kaipingGuy = kaipingOrderVo.getOtherMsg().getKaiPingGuy();
            kaipingGuy.setSignupTime(new Timestamp(new Date().getTime()));
            kaipingGuy.setDebt(new BigDecimal("0"));
            kaipingGuy.setInvoice(new BigDecimal("0"));
            int insert = kaipingGuyMapper.insert(kaipingGuy);
            if (insert == 1) {
                tempByKaipingGuyInsert = true;
            }
        }

        Integer kaipingguyId = null;
        if (kaipingOrderVo.getIsNewKaiPingGuy()) {
            QueryWrapper<KaipingGuy> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("kaipingguy_id");
            wrapper.last("LIMIT 1");
            List<KaipingGuy> kaipingGuys = kaipingGuyMapper.selectList(wrapper);
            kaipingguyId = kaipingGuys.get(0).getKaipingguyId();
        } else {
            tempByKaipingGuyInsert = true;
            kaipingguyId = kaipingOrderVo.getOtherMsg().getKaiPingGuy().getKaipingguyId();
        }
//
        ReturnMsg msg = new ReturnMsg();
        if (tempByKaipingGuyInsert) {
//              1、进行开平厂家扣款     计算总共要多少钱(单价成*张数)
            BigDecimal price = kaipingOrderVo.getOtherMsg().getPrice();
            Integer quantity = 0;
            List<KaipingOrderDetailVo> temp1 = kaipingOrderVo.getKaipingOrderDetailVoList();
            for (int i = 0; i < temp1.size(); i++) {
                KaipingOrderDetailVo kaipingOrderDetailVo = temp1.get(i);
                Integer quantity1 = kaipingOrderDetailVo.getQuantity();
                quantity = quantity1 + quantity;
            }

            BigDecimal countMoney = price.multiply(new BigDecimal(quantity));
            kaipingGuyMapper.updateKaipingGuyDebt(kaipingguyId, countMoney);
//          操作开平订单大表

            BigInteger kaipingLsh = LshUtil.getKaiPingNo1TypeLsh();
            Timestamp operateTime = new Timestamp(new Date().getTime());
            java.sql.Date processingTime = kaipingOrderVo.getOtherMsg().getProcessingTime();
            Integer warehouseId = kaipingOrderVo.getOtherMsg().getWarehouseId();
            String remark = kaipingOrderVo.getOtherMsg().getRemark();
            Integer rawMaterial = kaipingOrderVo.getOtherMsg().getRawMaterial();
            BigDecimal rawSpecification = kaipingOrderVo.getOtherMsg().getRawSpecification();
            BigDecimal rawWeigh = kaipingOrderVo.getOtherMsg().getRawWeigh();
            Integer juanbanQuantity = kaipingOrderVo.getOtherMsg().getJuanbanQuantity();
            KaipingOrder kaipingOrder = new KaipingOrder();

            kaipingOrder.setKaipingOrderId(kaipingLsh);
            kaipingOrder.setEmployeeId(employeeId);
            kaipingOrder.setMoney(countMoney);
            kaipingOrder.setInvoiceMoney(countMoney);
            kaipingOrder.setInvoiceIsSettled(0);
            kaipingOrder.setKaipingguyId(kaipingguyId);
            kaipingOrder.setWarehouseId(warehouseId);
            kaipingOrder.setRawMaterial(rawMaterial);
            kaipingOrder.setRawSpecification(rawSpecification);
            kaipingOrder.setRawWeigh(rawWeigh.multiply(new BigDecimal(juanbanQuantity)));
            kaipingOrder.setRemark(remark);
            kaipingOrder.setProcessingTime(processingTime);
            kaipingOrder.setOperateTime(operateTime);
            kaipingOrder.setPaymentIsSettled(0);
            kaipingOrder.setGiven(new BigDecimal("0"));
            kaipingOrder.setIsReconciliation(0);
            kaipingOrder.setIsWriteOff(0);
            kaipingOrder.setIsInvoice(0);
            kaipingOrder.setIsTiaoPiao(0);
            kaipingOrder.setTiaoPiaoId(null);
            kaipingOrder.setMoLingTou(0);
            kaipingOrderMapper.insert(kaipingOrder);

//            3、 操作开平订单细节表,需要当前大表的流水号
            List<KaipingOrderDetailVo> kaipingOrderDetailVoList = kaipingOrderVo.getKaipingOrderDetailVoList();
            ArrayList<KaipingDetail> kaipingDetailArrayList = new ArrayList<>();
            for (int i = 0; i < kaipingOrderDetailVoList.size(); i++) {
                KaipingOrderDetailVo orderDetailVo = kaipingOrderDetailVoList.get(i);
                KaipingDetail kaipingDetail = new KaipingDetail();
                kaipingDetail.setKaipingOrderId(kaipingLsh);
                kaipingDetail.setSmallTypeId(orderDetailVo.getLeibie());
                kaipingDetail.setSpecification(kaipingOrderVo.getOtherMsg().getRealSpecification().toString());
                kaipingDetail.setThickness(kaipingOrderVo.getOtherMsg().getRealSpecification());
                kaipingDetail.setLong1(orderDetailVo.getLong1());
                kaipingDetail.setWide(orderDetailVo.getWide());
                kaipingDetail.setHigh(orderDetailVo.getHeight());
                kaipingDetail.setQuantity(orderDetailVo.getQuantity());
                kaipingDetail.setPrice(price);
                kaipingDetail.setWay(4);
                kaipingDetailArrayList.add(kaipingDetail);
            }

            for (int i = 0; i < kaipingDetailArrayList.size(); i++) {
                KaipingDetail kaipingDetail = kaipingDetailArrayList.get(i);
                kaipingDetailMapper.insert(kaipingDetail);
            }
//            4、对库存表进行一系列更新
//            先把原料在库存中进行去除
            inventoryMapper.deleteById(kaipingOrderVo.getOtherMsg().getInventoryId());

            for (int i = 0; i < kaipingDetailArrayList.size(); i++) {
                KaipingDetail kaipingDetail = kaipingDetailArrayList.get(i);
                QueryWrapper<Inventory> firstWrapper = PingBanWrapperUtil(kaipingDetail, 3);
                List<Inventory> inventoryList = inventoryMapper.selectList(firstWrapper);
                if (!inventoryList.isEmpty()) {
                    Inventory inventory = inventoryList.get(0);
                    Integer temp = inventory.getQuantity() + kaipingDetail.getQuantity();//-5+6
                    if (temp > 0) {
                        inventoryMapper.deleteById(inventory.getInventoryId());
                        QueryWrapper<Inventory> secondWrapper = PingBanWrapperUtil(kaipingDetail, kaipingOrder.getWarehouseId());
                        List<Inventory> inventoryList1 = inventoryMapper.selectList(secondWrapper);
                        if (inventoryList1.isEmpty()) {
                            inventory.setInventoryId(null);
                            inventory.setWarehouseId(kaipingOrder.getWarehouseId());
                            inventory.setQuantity(temp);
                            inventoryMapper.insert(inventory);
                        } else {
                            Inventory inventory1 = inventoryList1.get(0);
                            Integer oldQuantity = inventory1.getQuantity();
                            Integer newQuantity = oldQuantity + temp;
                            inventory1.setQuantity(newQuantity);
                            inventoryMapper.updateById(inventory1);
                        }
                    } else if (temp == 0) {
                        inventoryMapper.deleteById(inventory.getInventoryId());
                    } else {
                        inventory.setQuantity(temp);
                        inventoryMapper.updateById(inventory);
                    }
                } else {
                    QueryWrapper<Inventory> threeWrapper = PingBanWrapperUtil(kaipingDetail, kaipingOrder.getWarehouseId());
                    List<Inventory> inventoryList2 = inventoryMapper.selectList(threeWrapper);
                    if (inventoryList2.isEmpty()) {
                        Inventory inventory3 = new Inventory();
                        inventory3.setSmallTypeId(kaipingDetail.getSmallTypeId());
                        inventory3.setWarehouseId(kaipingOrder.getWarehouseId());
                        inventory3.setSpecification(kaipingDetail.getSpecification());
                        inventory3.setThickness(kaipingDetail.getThickness());
                        inventory3.setLong1(kaipingDetail.getLong1());
                        inventory3.setWide(kaipingDetail.getWide());
                        inventory3.setHigh(kaipingDetail.getHigh());
                        inventory3.setQuantity(kaipingDetail.getQuantity());
                        inventory3.setWeight(new BigDecimal(0));
                        inventoryMapper.insert(inventory3);
                    } else {
                        Inventory inventory4 = inventoryList2.get(0);
                        Integer oldQuantity = inventory4.getQuantity();
                        Integer newQuantity = oldQuantity + kaipingDetail.getQuantity();
                        inventory4.setQuantity(newQuantity);
                        inventoryMapper.updateById(inventory4);

                    }
                }
            }
            msg.setMsg("添加开平订单成功");
            msg.setCode(1);
            return msg;

        } else {
            msg.setMsg("系统好像睡着了，注册新供应商失败");
            msg.setCode(0);
            return msg;
        }
    }

    @Override
    public List<KaipingOrder> kaipingFindRecoding(KaiPingByRecoding selectMsg) {
        Integer now = selectMsg.getCurrentPage();
        Integer size = selectMsg.getPageSize();
        now=(now-1)*size;

        Integer smallTypeId = selectMsg.getSmallTypeId();
        Integer warehouseId = selectMsg.getWarehouseId();
        BigDecimal specification = selectMsg.getSpecification();
        String kaipingguyName = selectMsg.getKaipingguyName();
        if (kaipingguyName != null && !kaipingguyName.equals("")){
            kaipingguyName="%"+kaipingguyName+"%";
        }
        Boolean showAllPayInvoice = selectMsg.getShowAllPayInvoice();
        Boolean showPay = selectMsg.getShowPay();
        Boolean showInvoice = selectMsg.getShowInvoice();
        BigDecimal weight = selectMsg.getWeight();
        List<java.sql.Date> timeZone = selectMsg.getTimeZone();
        java.sql.Date startDate =null;
        java.sql.Date endDate =null;
        if (timeZone!=null){
            startDate = timeZone.get(0);
            endDate = timeZone.get(1);
        }


        return kaipingOrderMapper.findALlMsg(smallTypeId, warehouseId, specification, weight, kaipingguyName, showAllPayInvoice, showPay, showInvoice, startDate, endDate);
    }

    @Override
    public Integer kaipingFindRecodingCount(KaiPingByRecoding selectMsg) {
        Integer now = selectMsg.getCurrentPage();
        Integer size = selectMsg.getPageSize();
        now=(now-1)*size;

        Integer smallTypeId = selectMsg.getSmallTypeId();
        Integer warehouseId = selectMsg.getWarehouseId();
        BigDecimal specification = selectMsg.getSpecification();
        String kaipingguyName = selectMsg.getKaipingguyName();
        if (kaipingguyName != null && !kaipingguyName.equals("")){
            kaipingguyName="%"+kaipingguyName+"%";
        }
        Boolean showAllPayInvoice = selectMsg.getShowAllPayInvoice();
        Boolean showPay = selectMsg.getShowPay();
        Boolean showInvoice = selectMsg.getShowInvoice();
        BigDecimal weight = selectMsg.getWeight();
        List<java.sql.Date> timeZone = selectMsg.getTimeZone();
        java.sql.Date startDate =null;
        java.sql.Date endDate =null;
        if (timeZone!=null){
            startDate = timeZone.get(0);
            endDate = timeZone.get(1);
        }
        return kaipingOrderMapper.kaipingFindRecodingCount(smallTypeId, warehouseId, specification, weight, kaipingguyName, showAllPayInvoice, showPay, showInvoice, startDate, endDate);
    }
}
